package gui.parta;

import java.nio.charset.StandardCharsets;

/**
 *
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
public class CRC16 {
    public static void main(String[] args) {
        System.out.println(getCRC(hexStringToString("31323341")));
    }

    public static String getCRC(byte[] bytes) {
        int CRC = 0X0000FFFF;
        final int POLYNOMIAL = 0X0000A001;
        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC = CRC ^ ((int) (bytes[i] & 0x000000ff));
            for (j = 0; j < 8; j++) {
                if ((CRC & 0X00000001) != 0) {
                    CRC = CRC >> 1;
                    CRC = CRC ^ POLYNOMIAL;
                } else {
                    CRC = CRC >> 1;
                }
            }
        }
        String result = Integer.toHexString(CRC).toUpperCase();
        if (result.length() != 4) {
            StringBuffer sb = new StringBuffer("0000");
            result = sb.replace(4 - result.length(), 4, result).toString();
        }
        return result.substring(2, 4) + result.substring(0, 2);
    }

    public static String getCRC(String hexData) {
        return getCRC(hexData.getBytes(StandardCharsets.UTF_8));
    }

    // 十六进制转字符串
    public static String hexStringToString(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
        }
        s = new String(baKeyword, StandardCharsets.UTF_8);
        return s;
    }
}
